<script setup>
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { ref } from 'vue'
import { ElMessage , ElMessageBox} from 'element-plus'
import { Download , Upload} from '@element-plus/icons-vue'

const genderOptions = ref([
  { label: '男', value: '男' },
  { label: '女', value: '女' }
]);

const custom = ref([
    {
        "userId": '',
        "userName": '',
        "password": '',
        "realName": '',
        "address":'',
        "phone": '',
        "sex": '',
        "age": '',
        "createTime": '',
        "updateTime": '',
        "role":''
    }
])

//模型
const customModel = ref({
  userId: '',
  userName: '',
  password: '',
  realName: '',
  address:'',
  phone: '',
  sex: '',
  age: '',
  role: ''
})

//搜索模型
const customSearchModel = ref({
  userName: '',
  realName: '',
  role: ''
})

//身份下拉选项
const roleOptions = ref([
  { label: '客户', value: '0' },
  { label: '管理员', value: '1' }
]);

//控制添加用户弹窗
const dialogVisible = ref(false)

//校验
const rules = ref({
    userName:[
        {required: true, message: '用户名不能为空', trigger: 'blur'},
        {min: 3, max: 20, message: '用户名长度必须在3-20位非空字符', trigger: 'blur'}
    ],
    password:[
        {required: true, message: '密码不能为空', trigger: 'blur'},
        {min: 6, max: 20, message: '密码长度必须在6-20位非空字符', trigger: 'blur'}
    ]
})

import { workCustomListService , workCustomAddService, workCustomUpdateService, workCustomDeleteService, workCustomSearchService, exportUserExcelService, importUserExcelService} from '@/api/work'
const workCustomList = async()=>{
    let result = await workCustomListService();
     custom.value = result.data;
}
workCustomList();

//调用添加接口
const addCustom = async()=>{
    let result = await workCustomAddService(customModel.value)
    if(result.code === 0){
        ElMessage.success('添加成功');
    }
    else{
        ElMessage.error('添加失败');
    }
    workCustomList();
    dialogVisible.value = false;
}

//控制标题的展示
const title = ref('')

//展示编辑弹窗
const showUpdate = (row)=>{
    dialogVisible.value = true;
    title.value = '编辑用户信息';
    customModel.value.userName = row.userName;
    customModel.value.realName = row.realName;
    customModel.value.address = row.address;
    customModel.value.phone = row.phone;
    customModel.value.sex = row.sex;
    customModel.value.age = row.age;
    customModel.value.userId = row.userId;
}

//调用修改接口
const updateCustom = async()=>{
    let result = await workCustomUpdateService(customModel.value);
    if(result.code === 0){
        ElMessage.success('编辑成功');
    }
    else{
        ElMessage.error('编辑失败');
    }
    await workCustomList();
    dialogVisible.value = false;
}

//清除信息
const clearData = ()=>{
    customModel.value={
        userId: '',
        userName: '',
        password: '',
        realName: '',
        address:'',
        phone: '',
        sex: '',
        age: ''
    }
}

//调用删除接口
const deleteCustom = (row)=>{
    ElMessageBox.confirm(
        '你确定要删除该用户信息吗?',
        '温馨提示',
        {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        }
    )
        .then(async () => {
            let result = await workCustomDeleteService(row.userId);
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
            workCustomList();
            })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '用户取消删除',
            })
        })
}

//按条件搜索
const search = async () => {
  const searchParams = {
    userName: customSearchModel.value.userName,
    realName: customSearchModel.value.realName,
    role: customSearchModel.value.role
  };
  try {
    const result = await workCustomSearchService(searchParams);
    
    // 更新表格数据
    custom.value = result.data || []; //"|| []"兜底处理，确保不会因为值为空而报错
    
    if (custom.value.length === 0) {
      ElMessage.info('未找到匹配的数据');
    }
  } catch (error) {
    ElMessage.error('搜索失败：' + error.message);
  }
};

//重置
const resetForm = () => {
    customSearchModel.value.userName = '';
    customSearchModel.value.realName = '';
    customSearchModel.value.role = '';
    workCustomList(); 
};

//导出信息
const handleExport = async () => {
  try {
    const response = await exportUserExcelService();
    // 将文件流处理为可下载的 Excel 文件
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '用户信息表.xlsx'; // 设置下载文件名
    link.click();
    window.URL.revokeObjectURL(url); // 释放 URL 对象
    ElMessage.success('导出成功');
  } catch (error) {
    ElMessage.error('导出失败：' + error.message);
    console.error('导出错误详情：', error);
  }
};

const importFile = ref(null);   //定义响应式变量存储选择的文件

// 处理文件选择（导入时）
const handleFileChange = (file) => {
  importFile.value = file.raw; // 保存选择的文件对象
  handleImport(); // 选择文件后直接调用导入逻辑
};

// 导入信息
const handleImport = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择要导入的文件');
    return;
  }
  try {
    const result = await importUserExcelService(importFile.value);
    if (result.code === 0) {
      ElMessage.success('导入成功');
      await workCustomList(); // 导入成功后重新获取列表
    } else {
      ElMessage.error('导入失败');
    }
  } catch (error) {
    ElMessage.error('导入出错：' + error.message);
  }
};
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>客户管理</span>
                <div class="extra">
                    <el-button type="primary" @click="dialogVisible=true; title='添加客户'; clearData()">添加客户</el-button>
                    <el-upload
                        class="upload-btn"
                        action="#" 
                        :auto-upload="false" 
                        :on-change="handleFileChange" 
                        :show-file-list="true" >
                    <el-button type="success" @click="handleImport"><el-icon><Upload /></el-icon> 导入客户信息</el-button>
                    </el-upload>
                    <el-button type="success" @click="handleExport"><el-icon><Download /></el-icon> 导出客户信息</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline :model="customSearchModel">
            <el-form-item label="用户名：" prop="userName">
                <el-input v-model="customSearchModel.userName" placeholder="请输入用户名称"></el-input>
            </el-form-item>

            <el-form-item label="真实姓名：" prop="realName">
                <el-input v-model="customSearchModel.realName" placeholder="请输入真实姓名"></el-input>
            </el-form-item>
            <el-form-item label="身份：" prop="role">
                <el-select v-model="customSearchModel.role" placeholder="请选择身份" clearable style="width: 200px">
                <el-option v-for="(item, index) in roleOptions" :key="index" :label="item.label" :value="item.value"></el-option>
                </el-select>  
            </el-form-item>
            
            <el-form-item>
                <el-button type="primary" @click="search">搜索</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="custom" style="width: 100%">
            <el-table-column label="序号" width="100" type="index"> </el-table-column>
            <el-table-column label="客户编号" prop="userId"></el-table-column>
            <el-table-column label="用户名" prop="userName"></el-table-column>
            <el-table-column label="真实姓名" prop="realName"></el-table-column>
            <el-table-column label="地址" prop="address"></el-table-column>
            <el-table-column label="手机号" prop="phone"></el-table-column>
            <el-table-column label="性别" prop="sex"></el-table-column>
            <el-table-column label="年龄" prop="age"></el-table-column>
            <el-table-column label="操作" width="100">
                <template #default ="{row}">
                    <el-button :icon="Edit" circle plain type="primary" @click="showUpdate(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteCustom(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 添加分类弹窗 -->
        <el-dialog v-model="dialogVisible" :title="title" width="30%">
            <el-form :model="customModel" :rules="rules" label-width="100px" style="padding-right: 30px">
                <el-form-item label="用户名" v-if="title==='添加客户'" prop="userName">
                    <el-input v-model="customModel.userName" minlength="1" maxlength="10"></el-input>
                </el-form-item>
                <el-form-item label="用户名" v-if="title==='编辑用户信息'"  prop="userName">
                    <el-input v-model="customModel.userName" minlength="1" maxlength="10" disabled></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="title === '添加客户'">
                    <el-input v-model="customModel.password" minlength="1" maxlength="15"></el-input>
                </el-form-item>
                <el-form-item label="真实姓名" prop="realName">
                    <el-input v-model="customModel.realName" minlength="1" maxlength="15"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="customModel.address" minlength="1" maxlength="15"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="customModel.phone" minlength="1" maxlength="15"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="customModel.sex">
                        <el-radio v-for="(item, index) in genderOptions" :key="index" :value="item.value">{{ item.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input v-model="customModel.age" minlength="1" maxlength="15"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
             <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="title==='添加客户'? addCustom(): updateCustom()"> 确认 </el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .header .extra {
        display: flex;
        align-items: center;
        gap: 8px;
    }
     .upload-btn {
        display: inline-flex;
        align-items: center;
    }
}
</style>